package cn.liu.jetpack_demo.pages

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import cn.liu.jetpack_demo.models.BottomBar
import cn.liu.jetpack_demo.routes.BottomNavGraph


@ExperimentalFoundationApi
@ExperimentalMaterial3Api
@Composable
fun MainPage() {
  val navController = rememberNavController()
  Scaffold(bottomBar = {
    bottomBarItems(navController = navController)
  }) {
    BottomNavGraph(navController = navController, modifier = Modifier.padding(it))
  }
}

@Composable
fun bottomBarItems(navController: NavHostController) {
  val pages = listOf(
    BottomBar.Home,
    BottomBar.Profile,
    BottomBar.Setting
  )

  val navBackStackEntry by navController.currentBackStackEntryAsState()
  val currentDetination = navBackStackEntry?.destination

  BottomAppBar {
    pages.forEach { page ->
      AddItem(
        page = page,
        currentDestination = currentDetination,
        navController = navController
      )
    }
  }
}

@Composable
fun RowScope.AddItem(
  page: BottomBar,
  currentDestination: NavDestination?,
  navController: NavHostController
) {
  NavigationBarItem(label = {
    Text(text = page.title)
  }, icon = {
    Icon(imageVector = page.icon, contentDescription = "Navigation Icon")
  },
    selected = currentDestination?.hierarchy?.any {
      it.route == page.route
    } == true,
    onClick = {
      navController.navigate(page.route) {
        popUpTo(navController.graph.findStartDestination().id)
        launchSingleTop = true
      }
    }
  )
}

